//
//  BadgeView.swift
//  开心微博
//
//  Created by 郑开心 on 15/12/6.
//  Copyright © 2015年 郑开心. All rights reserved.
//

import UIKit

class BadgeView: UIButton {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    let BadgeViewFont = UIFont.systemFontOfSize(14)
    
    var badgeValue : String?{
        didSet{
            setBadgeValue()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.userInteractionEnabled = true
        self.setBackgroundImage(UIImage(named: "main_badge"), forState: UIControlState.Normal)
        self.titleLabel?.font = BadgeViewFont
        self.sizeToFit()
    }

    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setBadgeValue(){
        if let badgeValue1 = badgeValue {
            if badgeValue1.characters.count == 0 || badgeValue1 == "0"{
                self.hidden = true
            }else{
                self.hidden = false
            }
            let size = NSString(string: badgeValue1).sizeWithAttributes([NSFontAttributeName:BadgeViewFont])
            
            if size.width > self.width {
                self.setImage(UIImage(named: "new_dot"), forState: UIControlState.Normal)
                self.setTitle(nil, forState: UIControlState.Normal)
                self.setBackgroundImage(nil, forState: UIControlState.Normal)
            }else{
                self.setImage(nil, forState: UIControlState.Normal)
                self.setTitle(badgeValue1, forState: UIControlState.Normal)
                self.setBackgroundImage(UIImage(named: "main_badge"), forState: UIControlState.Normal)
            }

        }else{
            self.hidden = true
        }
    }
    
}
